<template lang="html">
  <article id="views-orders">
    <ul class="orders-header">
      <li
        :class="{ active: index === curIndex }"
        class="header-item"
        v-for="(item, index) in tablist"
        @click="curIndex = index"
      >
        {{item.value}}
      </li>
    </ul>
    <div class="orders-container" @touchmove="touchmove">
      <PullRefresh
        :on-refresh="refreshList"
        :isLock="isPullRefreshLock"
      >
        <OrderList
          :orderList="currentList"
          :status="status"
          :canLoadMore="canLoadMore"
          v-on:loadmore="loadmore"
          v-on:onClickItem="goToDetail"
        ></OrderList>
      </PullRefresh>
    </div>
  </article>
</template>

<script>
import superagent from 'superagent'
import utils from '@/lib/utils'
import authMiddleware from '@/lib/auth-middleware'

const INDEX_TO_STATUS = [
  'remain', 'finish', 'cancel'
]

export default {
  name: 'PageOrderList',
  components: {
    OrderList: require('@/components/orders_order_list'),
    PullRefresh: require('@/components/common_pull_refresh/')
  },
  data(){
    return {
      curIndex: 0,
      containerEle: null,
      isPullRefreshLock: true,
      pageMark: {
        1: 1,
        2: 1,
        3: 1
      },//标记每个订单列表当前页数
      loadMoreMark: {
        1: 1,
        2: 1,
        3: 1
      },//标记是否可加载更多
      tablist: [
        { value: '待上课' },
        { value: '已完成' },
        { value: '退课' },
      ],
      orderCollection: {
        [INDEX_TO_STATUS[0]]:[],
        [INDEX_TO_STATUS[1]]: [],
        [INDEX_TO_STATUS[2]]: []
      }
    }
  },
  computed: {
    currentList(){
      let idx = this.curIndex
      return this.orderCollection[INDEX_TO_STATUS[idx]]
    },
    currentPage(){
      let status = this.curIndex + 1
      return this.pageMark[status]
    },
    canLoadMore(){
      let status = this.curIndex + 1
      return this.loadMoreMark[status]
    },
    status(){
      let idx = this.curIndex
      return INDEX_TO_STATUS[idx]
    },
  },
  methods: {
    touchmove(){
      let isUpper = this.containerEle.scrollTop == 0
      if(isUpper){
        this.isPullRefreshLock = false
      } else if(!this.isPullRefreshLock){
        this.isPullRefreshLock = true
      }
    },
    goToDetail(detail){
      this.$router.push({ path: `/order/${detail.orderId}` })
    },
    //点击加载更多
    loadmore(){
      let index = this.curIndex,
          status = index + 1

      this.getOrderList(status, this.currentPage + 1)
      .then(data => {
        let orderList = data.orders[status]
        if(orderList.length > 0){
          this.pageMark[status]++
          let preList = this.orderCollection[INDEX_TO_STATUS[index]].slice(0)
          this.orderCollection[INDEX_TO_STATUS[index]] = preList.concat(orderList)
          if(orderList.length < 10){
            utils.toast('已加载全部订单')
            this.loadMoreMark[status] = 0
          }
        } else {
          utils.toast('已加载全部订单')
          this.loadMoreMark[status] = 0
        }
      })
    },
    //下拉刷新列表： 1.刷新当前分类列表；2.重置当前分类的canLoadMore与page
    refreshList(){
      return new Promise((resolve, reject) => {
        let index = this.curIndex

        this.$store.dispatch('toggleIsLoading')

        this.getOrderList(index + 1)
        .then(orderList => {
          resolve()
          this.orderCollection[INDEX_TO_STATUS[index]] = orderList.orders[index + 1]
          this.resetStatus(index + 1)
          this.$store.dispatch('toggleIsLoading')
          this.isPullRefreshLock = true
        })
        .catch(e => {
          reject()
        })
      })
    },
    resetStatus(status){
      this.pageMark[status] = 1
      this.loadMoreMark[status] = 1
    },
    getOrderList(status, page){
      let opt = {}
      if(status){
        opt.status = status
      }
      if(page){
        opt.page = page
      }
      return new Promise((resolve, reject) => {
        superagent.get('/api/order/my_all')
          .use(authMiddleware())
          .query(opt)
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getOrderList error'))
              }
            }
          })
      })
    },
  },
  created(){
    this.getOrderList()
    .then(orderCollection => {
      for(let i = 0;i < 3;i++){
        let curList = orderCollection.orders[i + 1]
        if(curList.length < 10){
          this.loadMoreMark[i + 1] = 0
        }
        this.orderCollection[INDEX_TO_STATUS[i]] = curList
      }
    })
  },
  mounted(){
    this.containerEle = this.$el.querySelector('.orders-container')
  }
}
</script>

<style lang="scss" scoped>
@import "../css/config";
$border-color: #1b1b1f;
$header-height: 70px;
$padding-top: 35px;
$padding-left: 25px;
#views-orders{
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: $padding-top+$header-height+30px $padding-left $padding-top;
  background-color: $common-bg;
  overflow: hidden;
  .orders-header{
    position: absolute;
    top: $padding-top;
    left: $padding-left;
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    width: 700px;
    height: $header-height;
    line-height: $header-height;
    box-sizing: border-box;
    border: 2px solid $border-color;
    border-radius: 21px;
    overflow: hidden;
    .header-item{
      flex: 1 1 33.3%;
      text-align: center;
      box-sizing: border-box;
      background: #fff;
      &.active{
        color: $common-red;
        background-color: $border-color;
      }
    }
    .header-item:nth-child(2){
      border-left: 2px solid $border-color;
      border-right: 2px solid $border-color;
    }
  }
  .orders-container{
    width: 100%;
    height: 100%;
    overflow: scroll;
  }
}
</style>
